﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace VCommons
{
    public class StringAction
    {
        #region  格式化html文档
        /// <summary>
        /// 格式化html文档
        /// </summary>
        /// <remarks>
        /// Created By :王彦忠  
        /// Created Date：2011-10-29
        /// Modify By:
        /// Modify Date:
        /// Modify Reason:
        /// </remarks>
        /// <param name="strHTML"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static string FormatStringByXML(string strHTML, XElement xml)
        {
            if (xml.HasAttributes)
            {
                foreach (Match match in Regex.Matches(strHTML, @"(\{)(:?\w+)(\})", RegexOptions.IgnoreCase))
                {
                    strHTML = strHTML.Replace(match.Value, GetAttributeValue(xml, match.Value.Replace("{", "").Replace("}", "")));
                }
                return strHTML;
            }
            else
            {
                return "<br/>";
            }
        }
        #endregion

        #region 获取一个XML对象的属性
        /// <summary>
        /// 获取一个XML对象的属性
        /// </summary>
        /// <remarks>
        /// Created By :王彦忠  
        /// Created Date：2011-10-29
        /// Modify By:
        /// Modify Date:
        /// Modify Reason:
        /// </remarks>
        /// <param name="xml">xml对象</param>
        /// <param name="strField">属性名称</param>
        /// <returns></returns>
        public static string GetAttributeValue(XElement xml, string strField)
        {
            if (null != xml)
            {
                var node = xml.Attribute(strField);
                if (null != node)
                {
                    return node.Value;
                }
                else
                {
                    return "{" + strField + "}";
                }
            }
            else
            {
                return "{" + strField + "}";
            }
        }
        #endregion
    }
}
